package com.sagar.gcma;

import static com.sagar.gcma.CommonUtilities.SENDER_ID;

import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService{

	public GCMIntentService() {
		super(SENDER_ID);
	}
	
	private static final String TAG = "===GCMIntentService===";
	
	
	@Override
	protected void onRegistered(Context arg0, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
	}
	
	@Override
	protected void onUnregistered(Context arg0, String arg1) {
		Log.i(TAG, "unregistered = "+arg1);
	}
	
	@Override
	protected void onMessage(Context arg0, Intent arg1) {
		Log.i(TAG, "new message= "+arg1.getExtras().getString("message")+"  "+
				arg1.getExtras().getString("tickerText")+"  "+
				arg1.getExtras().getString("contentTitle")+"  "+
				arg1.getExtras().getString("contentText"));
				mostrarNotificacion(arg0, ""+arg1.getExtras().getString("message"));
		//GenerateNotification(arg0, arg1.getExtras().getString("message"));
	}
	
	private void mostrarNotificacion(Context context, String msg)
	{
	    //Obtenemos una referencia al servicio de notificaciones
	    String ns = Context.NOTIFICATION_SERVICE;
	    NotificationManager notManager =
	        (NotificationManager) context.getSystemService(ns);
	 
	    //Configuramos la notificación
	    int icono = android.R.drawable.stat_sys_warning;
	    CharSequence textoEstado = "Alerta!";
	    long hora = System.currentTimeMillis();
	 
	    Notification notif =
	        new Notification(icono, textoEstado, hora);
	 
	    //Configuramos el Intent
	    Context contexto = context.getApplicationContext();
	    CharSequence titulo = "Nuevo Mensaje";
	    CharSequence descripcion = msg;
	 
	    Intent notIntent = new Intent(contexto,
	        GCMIntentService.class);
	 
	    PendingIntent contIntent = PendingIntent.getActivity(
	        contexto, 0, notIntent, 0);
	 
	    notif.setLatestEventInfo(
	        contexto, titulo, descripcion, contIntent);
	    
	    notif.defaults |= Notification.DEFAULT_SOUND;
	    //AutoCancel: cuando se pulsa la notificaión ésta desaparece
	    notif.flags |= Notification.FLAG_AUTO_CANCEL;
	    
	    Random r = new Random();

	 
	    //Enviar notificación
	    notManager.notify(r.nextInt(10), notif);
	}
	


	@Override
	protected void onError(Context arg0, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
	}
	
	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		return super.onRecoverableError(context, errorId);
	}
}

